import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const takeawayStore = createSlice({
  name: "takeaway",
  initialState: {
    foodList: [],
    activeIndex: 0,
    cartList: []
  },
  reducers: {
    setFoodList(state, action) {
      state.foodList = action.payload;
    },
    setActiveIndex(state, action) {
      state.activeIndex = action.payload;
    },
    addCart(state, action) {
      let item = state.cartList.find(item => item.id === action.payload.id);
      if (item) {
        item.count++
      } else {
        action.payload.count = 1
        state.cartList.push(action.payload)
      }
    },
    increCount(state, action) {
      const cart = state.cartList.find(item => item.id === action.payload.id)
      cart.count++
    },
    decCount(state, action) {
      const cart = state.cartList.find(item => item.id === action.payload.id)
      if (cart.count <= 0) {
        return
      }
      cart.count--
    },
    clearCart(state) {
      state.cartList = []
    }
  }
});
const reducer = takeawayStore.reducer
const {
  setFoodList,
  setActiveIndex,
  addCart,
  increCount,
  decCount,
  clearCart
} = takeawayStore.actions;
const fetchFoodList = () => {
  return async (dispatch) => {
    const res = await axios.get("http://localhost:3004/takeaway");
    dispatch(setFoodList(res.data));
  }
}

export {
  fetchFoodList,
  setActiveIndex,
  addCart,
  increCount,
  decCount,
  clearCart
};
export default reducer